package cn.johnyu.server;

import cn.johnyu.client.Client;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ChatServer implements Runnable{
    private ServerSocket serverSocket;

    public void start(int port) throws Exception{

        serverSocket=new ServerSocket(port);
        //在一个子线程中提交run方法，目的仅仅是避免占用主线程
        Executors.newSingleThreadExecutor()
                .submit(this);

    }
    @Override
    public void run() {
        ExecutorService service = Executors.newFixedThreadPool(10);
        while (true){
            try {
                Socket socket=serverSocket.accept();
                System.out.println("主线程监听到连接：：："+socket.getRemoteSocketAddress().toString());
                //在一个线程中处理用户的交互逻辑（Thread per Request）
                service.submit(new Client(socket));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
